﻿using System.Reflection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.OData.Edm;
using OData.MinimalApi.Configuration;
using OData.MinimalApi.Endpoints;

namespace OData.MinimalApi.Extensions;

public static class ODataEndpointExtensions
{
	public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly)
	{
		ServiceDescriptor[] serviceDescriptors = assembly
			.DefinedTypes
			.Where(type => type is { IsAbstract: false, IsInterface: false } &&
			               type.IsAssignableTo(typeof(IOdataEndpoint)))
			.Select(type => ServiceDescriptor.Transient(typeof(IOdataEndpoint), type))
			.ToArray();
		services.TryAddEnumerable(serviceDescriptors);

		return services;
	}

	public static IApplicationBuilder MapOdataEndpoints(
		this WebApplication app,
		IEdmModel model,
		RouteGroupBuilder? routeGroupBuilder = null)
	{
		IEnumerable<IOdataEndpoint> endpoints = app.Services.GetRequiredService<IEnumerable<IOdataEndpoint>>();
		IEndpointRouteBuilder builder = routeGroupBuilder is null ? app : routeGroupBuilder;
		foreach (IOdataEndpoint endpoint in endpoints)
		{
			endpoint.MapEndpoint(builder, model);
		}
		return app;
	}
}
